<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\Tools\ExcelImport;
use App\Admin\Extensions\Tools\UserGender;
use App\Baby;

use App\CourseSubscribe;
use App\Town;
use App\Events\SendTemplateMsg;
use App\Http\Controllers\Wechat;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use App\Admin\Extensions\ExcelExpoter;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class BabyController extends Controller
{
    use ModelForm;
    protected $excel_file_input = 'import_excel';

    /**
     * Index interface.
     *
     * @return Content
     */

    public function update($id)
    {
        $baby = Baby::find($id);
        $data = $_POST;

        $result = $this->form()->update($id);
        if (isset($data['state']) && $data['state'] != $baby->state && env('APP_ENV') == 'production') {
            $templates = [
                1 => Wechat::VALIDATION_TEMPLATE_ID,
                2 => Wechat::REGIST_FAILED_TEMPLATE_ID,
            ];
            $state_msg = ['0' => '未审核', '1' => '恭喜您，通过审核！每个宝宝可以预约三次课程！请在微信菜单栏“悦宝-最新课程”中查看课程，在微信菜单栏“有约-课程预约”中预约课程。', '2' => '审核失败'];


            $msg_data = [
                '1' => [
                    'first' => $state_msg[$data['state']],
                    'keyword1' => date('Y-m-d H:i', time()),
                    'keyword2' => $baby->guardian,
                    'remark' => $data['validate_msg']
                ],
                '2' => [
                    'first' => $state_msg[$data['state']],
                    'keyword1' => $data['validate_msg'],
                    'keyword2' => date('Y-m-d H:i', time()),
                    'remark' => '你可以在“有约->家长注册”中重新修改资料并提交'
                ]
            ];

            event(new SendTemplateMsg( // TODO 调试环境不能使用模板消息
                $templates[$data['state']],
                $baby->wechat_user->open_id,
                json_encode($msg_data[$data['state']])
            ));
        }
        return $result;
    }


    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('宝宝资料');
            $content->description('列表');
            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $baby = Baby::find($id);

            $content->header('宝宝资料');
            $content->description('编辑');

            $validations_options = [
                '0' => ['1' => '通过审核', '2' => '拒绝通过'],
                '1' => [],
                '2' => ['1' => '通过审核', '2' => '拒绝通过'],
            ];

            $content->body($this->form($validations_options[$baby->state])->edit($id));

        });
    }

    /**
     * 获取宝宝的课程
     * @param $id
     * @return Content
     */
    public function courses($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $baby = Baby::find($id);
            $content->header( '<a href="/admin/baby">所有宝宝</a>');
            $content->description($baby->name);
            $content->body(Admin::grid(CourseSubscribe::class, function (Grid $grid) use ($baby) {
                $grid->disableFilter();
                $grid->disableExport();
                $grid->model()->where('baby_id', $baby->id);
                $grid->disableActions();
                $grid->disableCreation();
                $grid->disableRowSelector();
                $grid->id('ID')->sortable();
                $grid->column('baby.name', '宝宝名');
                $grid->column('course.name', '课程名');
                $grid->column('course_time', '上课时间');
                $grid->created_at('预约时间');
            }));
        });
    }


    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('宝宝资料');
            $content->description('新增');

            $content->body($this->form());
        });
    }

    public function import_from_excel()
    {
        $result = false;
        $data = [];
        $file = $_FILES[$this->excel_file_input];
        if (!file_exists($file['tmp_name'])) {
            $msg = '上传文章不能为空';
        } else {
            $msg = '读取数据失败';
            Excel::load($file['tmp_name'], function ($reader) use (&$msg, &$data) {
                $msg = '数据读取成功';
                $table = $reader->all();
                foreach ($table as $row) {
                    if (is_array($row['birth'])) {
                        $row['birth'] = $row['birth']['date'];
                    }

                    $baby = new Baby();
                    $baby->name = $row['name'];
                    $baby->birth = $row['birth'];
                    $baby->sex = $row['sex'] === '男' ? 1 : 0;
                    $baby->guardian = $row['guardian'];
                    $baby->number = $row['number'];
                    $baby->habitual_residence = $row['habitual_residence'];
                    $baby->living_area = $row['living_area'];
                    $data[] = $baby->save();
                }
            });
        }
        return json_encode(compact('result', 'msg', 'data'));
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Baby::class, function (Grid $grid) {
            $towns = DB::table('towns')->select()->get()->all();
            $towns = array_combine(array_column($towns, 'id'), array_column($towns, 'name'));

            $grid->disableCreation();
            $grid->actions(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->setEditTitle('编辑审核用户');
                    $batch->disableDelete();
                });
            });

            $grid->exporter(new ExcelExpoter($grid,
                'baby-' . date('Y-m-d', time()),
                ['id', 'name', 'sex', 'birth', 'guardian', 'tel', 'habitual_residence', 'town_id', 'state'],
                ['sex' => ['0' => '女', '1' => '男'], 'state' => ['0' => '未审核', '1' => '通过审核', '2' => '拒绝通过'], 'town_id' => $towns],
                ['ID', '宝宝名字', '性别', '出生日期', '家长姓名', '联系电话', '户籍所在地', '所属村居', '审核状态']
            ));

            $grid->actions((function ($actions) {
                $baby_id = $actions->getKey();
                $actions->setEditTitle('编辑审核用户');
                $actions->disableDelete();
                $actions->prepend('<a title="查看选择的课程" href="/admin/baby/' . $baby_id . '/courses"><i class="fa fa-search"></i></a>');
            }));
            $state_msg = ['0' => '未审核', '1' => '通过审核', '2' => '拒绝通过'];

            $grid->filter(function ($filter) use ($state_msg, $towns) {
                $filter->disableIdFilter();
                $filter->like('name', '宝宝名字');
                $filter->between('birth', '出生')->date();
                $filter->equal('state', '状态')->select($state_msg);
                $filter->equal('town_id', '所属村居')->select($towns);
            });

            $grid->column('name', '宝宝名字');
            $grid->column('birth', '出生日期');
            $grid->sex('性别')->display(function ($sex) {
                return $sex ? '男' : '女';
            });
            $grid->column('guardian', '家长姓名');
            $grid->column('tel', '联系电话');
            $grid->column('habitual_residence', '户籍所在地');
            $grid->column('town.name', '所属村居');
            $grid->column('state', '审核状态')->display(function ($state) use ($state_msg) {
                $state_msg = ['0' => '未审核', '1' => '通过审核', '2' => '拒绝通过'];
                return $state_msg[$state];
            });
            $grid->subscribes('已选课程')->display(function ($subs) {return count($subs);});


//            $grid->created_at('创建时间');
//            $grid->updated_at('更新时间');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($validations = [])
    {
        return Admin::form(Baby::class, function (Form $form) use ($validations) {

            $towns = DB::select('select id, name from towns');
            $towns = array_combine(array_column($towns, 'id'), array_column($towns, 'name'));


            $form->display('id', 'ID');
            $form->text('name', '宝宝名字');

            $form->radio('sex', '性别')->options(['1' => '男', '0' => '女'])->default('0');

            $form->date('birth', '宝宝生日');
            $form->text('guardian', '家长姓名');
            //$form->mobile('number', '家长手机');
            $form->mobile('tel', '联系电话');
            $form->text('habitual_residence', '户籍所在地');
//            $form->text('living_area', '所属村居');
            $form->select('town_id', '村居')->options($towns);
            // $state_msg = ['0'=>'未审核','1'=>'通过审核', '2'=>'拒绝通过'];
            // $form->radio('state','用户审核')->options($state_msg);
            if (!empty($validations)) {
                $form->radio('state', '用户审核')->options($validations);
                $form->text('validate_msg', '审核留言');
            } else {
                $form->display('state', '用户审核')->with(function () {
                    return '已经通过审核';
                });
            }

//            $form->file('file');


//            $form->display('created_at', 'Created At');
//            $form->display('updated_at', 'Updated At');
        });
    }
}
